package com.zgjkhis.modules.system.rest;

import com.zgjkhis.domain.PageResult;
import com.zgjkhis.exception.ServiceException;
import com.zgjkhis.logging.aop.log.Log;
import com.zgjkhis.modules.security.security.LoginUserUtil;
import com.zgjkhis.modules.system.domain.Supplier;
import com.zgjkhis.modules.system.service.SupplierService;
import com.zgjkhis.modules.system.service.dto.SupplierDto;
import com.zgjkhis.modules.system.service.dto.SupplierQueryCriteria;
import com.zgjkhis.modules.util.CharUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @date 2018-11-23
 */
@Api(tags = "库房管理：供应商管理")
@RestController
@RequestMapping("/api/supplier")
public class SupplierController {

    private static final String ENTITY_NAME = "supplier";
    private final SupplierService supplierService;

    public SupplierController(SupplierService supplierService) {
        this.supplierService = supplierService;
    }


    @Log("查看单个供应商")
    @GetMapping(value = "/detail")
    @ApiOperation("查看单个供应商")
    //    @PreAuthorize("@el.check('supplier:datail')")
    public ResponseEntity<Object> getDetail(String id) {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        return new ResponseEntity<>(supplierService.findDetailById(id), HttpStatus.OK);
    }

    @Log("新增供应商")
    @ApiOperation("新增供应商")
    @PostMapping(value = "/add")
//    @PreAuthorize("@el.check('supplier:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Supplier resources) {
        if (resources.getId() != null) {
            throw new ServiceException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        return new ResponseEntity<>(supplierService.save(resources), HttpStatus.OK);
    }

    @Log("修改供应商")
    @ApiOperation("修改供应商")
    @PostMapping(value = "/update")
//    @PreAuthorize("@el.check('supplier:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Supplier resources) {
        supplierService.saveOrUpdate(resources);
        return ResponseEntity.ok(true);
    }

    @Log("查询供应商")
    @ApiOperation("查询供应商")
    @GetMapping(value = "/getSuppliers")
//    @PreAuthorize("@el.check('supplier:list')")
    public ResponseEntity<PageResult<SupplierDto>> getSuppliers(SupplierQueryCriteria criteria, Pageable pageable) {
        criteria.setPharmacyId(LoginUserUtil.getPharmId());
        return new ResponseEntity<>(supplierService.queryAll(criteria, pageable), HttpStatus.OK);
    }

}
